
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/bean/tongxunlubean.dart';
import 'package:flutter_hotwork/homepage/BaseTitleBar.dart';
import 'package:flutter_hotwork/homepage/BaseViewBar.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';

import '../Login.dart';
import '../Myapplication.dart';
import '../Toast.dart';
import 'AtUserProvider.dart';
var firstrefresh =0;
tongxunlubean txbean;
List<Records> searchbean = new List();
class TongxunluScreen extends StatefulWidget {
  @override
  TongxunluState createState() => new TongxunluState();


}

class TongxunluState extends State<TongxunluScreen> {


  void getHotUserCount() async {
    try {
      Response response;

      if(MyApplication.loginuserinfo.userInfo.amHotuser==0){
        response = await DioUtils.dio.get(
            DioUtils.API_PREFIX + "/sys/user/list?pageSize=100&amHotuser=1");
      }else{
        response = await DioUtils.dio.get(
            DioUtils.API_PREFIX + "/sys/user/list?pageSize=100&amHotuser=1&username=*"+MyApplication.loginuserinfo.userInfo.username+"*");
      }



      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      if (base.code == 0) {
        txbean = tongxunlubean.fromJson(base.result);
        getTongxun2();
        // if(firstrefresh==0){
        //   setState(() {
        //     firstrefresh+=1;
        //   });
        // }
      } else if(base.code == 500){
        LocalToast.toast(context,msg:"会话超时，请重新登陆！");
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(
              builder: (context) => new MyHomePage()),
              (route) => route == null,
        );
      } else {
         LocalToast.toast(context,msg: base.message);
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      //  LocalToast.toast(context,msg: "网络错误");
      print('请求出错：' + e.toString());
    }
  }

  void getTongxun2() async {
    try {
      Response response;
      if(MyApplication.loginuserinfo.userInfo.amHotuser==0){
        response = await DioUtils.dio.get(
            DioUtils.API_PREFIX + "/sys/user/list?pageSize=100");
      }else{
        response = await DioUtils.dio.get(
            DioUtils.API_PREFIX + "/sys/user/list?pageSize=100&username=*"+MyApplication.loginuserinfo.userInfo.username+"*");
      }

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      if (base.code == 0) {
        tongxunlubean txbean2 = tongxunlubean.fromJson(base.result);
        txbean.records.addAll(txbean2.records);
        if(firstrefresh==0){
          setState(() {
            firstrefresh+=1;
          });
        }
      } else if(base.code == 500){
        LocalToast.toast(context,msg:"会话超时，请重新登陆！");
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(
              builder: (context) => new MyHomePage()),
              (route) => route == null,
        );
      } else {
        LocalToast.toast(context,msg: base.message);
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      //  LocalToast.toast(context,msg: "网络错误");
      print('请求出错：' + e.toString());
    }
  }
  final textEditingController = TextEditingController();
  @override
  Widget build(BuildContext context) {

    if(firstrefresh==0) {
      getHotUserCount();
    }
    ScrollController controller = ScrollController();

    textEditingController.addListener(() {
    print('input:${textEditingController.text}');

    searchbean.clear();
    for(int i = 0;i<txbean.records.length;i++){
        if(txbean.records[i].realname.contains(textEditingController.text)){
          searchbean.add(txbean.records[i]);
        }
    }
    setState(() {

    });
    });
    double rpx = MediaQuery
        .of(context)
        .size
        .width / 750;
    return Scaffold(

      appBar: new BaseViewBar(
          childView: new BaseTitleBar(
            "通讯录",
            leftIcon: '',
            rightIcon: "",
            rightClick: () {
              print("点击了右边干嘛啊。。。哦");
            },
            leftClick: () {
              print("点击了左边干嘛啊。。。哦");
            },
          ),
          preferredSize: Size.fromHeight(50.0)),
      body:
          Card(
        color: Color(0xFFF4F4F4),
        child: Column(
          children: [
            Container(
              height: 30,
              margin: EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 10),
              width: rpx * 600,
              padding: EdgeInsets.only(left: 10, top: 0, right: 0, bottom: 0),
              decoration: BoxDecoration(
                border: new Border.all(color: Color(0xFF9E9E9E), width: 0.5),
                // 边色与边宽度
                color: Colors.white,
                // 底色
                //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                borderRadius: BorderRadius.all(Radius.circular(15)),
              ),
              child:
              TextField(
                controller: textEditingController,
                style: TextStyle(color: Colors.grey),
//                            controller: phoneController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(10.0),
                  icon: Icon(Icons.search),
                  hintText: '搜索联系人',
                  hintStyle: TextStyle(color: Colors.grey),
//                            helperText: '请输入注册的手机号',
                  border: InputBorder.none,
                ),
                autofocus: false,
              ),

            ),
            Expanded(
              child:
              genUserList(context, controller)
              ,

            ),

          ],
        ),
      ),

    );
  }

  genUserList(context, controller) {

    if(searchbean.length>0&&textEditingController.text.length>0){
      return  genContentList(
          searchbean, context, controller
      );
    }else{
      if(null!=txbean&&null!=txbean.records){
        return  genContentList(
            txbean.records, context, controller
        );
      }else{
        return Container();
      }

    }
  }

  genContentList(List<Records> records, BuildContext context, controller) {
    double rpx = MediaQuery
        .of(context)
        .size
        .width / 750;
    return ListView.builder(
        shrinkWrap: true,
        controller: controller,
        itemCount:  records.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(

            decoration: BoxDecoration(
                color: Colors.white
            ),
            height: 120 * rpx,
            child:
            Column(
              children: [

                Row(
                  crossAxisAlignment:CrossAxisAlignment.center,

                  children: <Widget>[
                    Container(width: 80*rpx, child: CircleAvatar(backgroundImage:
                    // records[index].avatar!=null&&records[index].avatar.length>0?
                    // NetworkImage(
                    //     DioUtils.API_PREFIX+"/sys/common/view/"+records[index].avatar
                        // DioUtils.API_PREFIX+"/"+records[index].avatar
                    // ):
                    AssetImage('images/basepeopleicon.png')
                      ,)),
                    Container(
                      height: 115 * rpx,
                      padding: EdgeInsets.only(left: 20 * rpx),
                      width: 620 * rpx,
                      child: Row(
                        crossAxisAlignment:CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            width: 200 * rpx,
                            alignment: Alignment.centerLeft,
                            child: Text(( records[index]).realname, style: TextStyle(
                                fontSize: 32 * rpx, color: Colors.black),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis),
                          ),
                          Container(
                            width: 100 * rpx,
                            alignment: Alignment.centerRight,
                            child:
                            Text(
                              ( records[index]).statusDictText,
                              style: TextStyle(color: Colors.grey[500],
                                  fontSize: 32 * rpx),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Container(
                            width: 300 * rpx,
                            alignment: Alignment.centerRight,
                            child:
                            Text(
                              ( records[index]).phone,
                              style: TextStyle(color: Colors.grey[500],
                                  fontSize: 32 * rpx),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      )
                      ,),

                  ],
                ),
                Container(
                  height:0.5,
                  margin: EdgeInsets.only(left: 10,right: 10,top: 0,bottom: 0),
                  color: Colors.grey,
                ),
              ],
            ),

          );
        }
    );
  }
}